const TOKEN_KEY = 'token';

/**
 * 保存 Token
 * @param token 令牌
 * @param autoLogin 是否自动登录 (true: localStorage, false: sessionStorage)
 */
export const setToken = (token: string, autoLogin: boolean) => {
  if (autoLogin) {
    localStorage.setItem(TOKEN_KEY, token);
  } else {
    sessionStorage.setItem(TOKEN_KEY, token);
  }
};

/**
 * 获取 Token，优先从 sessionStorage 读取，若没有再从 localStorage 读取
 * @returns {string | null} 返回 Token 或 null
 */
export const getToken = (): string | null => {
  return sessionStorage.getItem(TOKEN_KEY) || localStorage.getItem(TOKEN_KEY);
};

/**
 * 清除 Token
 */
export const clearToken = () => {
  localStorage.removeItem(TOKEN_KEY);
  sessionStorage.removeItem(TOKEN_KEY);
};
